/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.YxAppdictService;
import co.yixiang.modules.user.domain.YxAuthentication;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.dto.IdCardResult;
import co.yixiang.modules.websocket.Websocket;
import co.yixiang.utils.DataUtil;
import co.yixiang.utils.VerifyUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import co.yixiang.dozer.service.IGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.modules.user.service.YxAuthenticationService;
import co.yixiang.modules.user.service.dto.YxAuthenticationDto;
import co.yixiang.modules.user.service.dto.YxAuthenticationQueryCriteria;
import co.yixiang.modules.user.service.mapper.YxAuthenticationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @author yhh
* @date 2020-09-15
*/
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "yxAuthentication")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxAuthenticationServiceImpl extends BaseServiceImpl<YxAuthenticationMapper, YxAuthentication> implements YxAuthenticationService {

    private final IGenerator generator;
    private final YxAppdictService yxAppdictService;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(YxAuthenticationQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxAuthentication> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxAuthenticationDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<YxAuthentication> queryAll(YxAuthenticationQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxAuthentication.class, criteria));
    }


    @Override
    public void download(List<YxAuthenticationDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxAuthenticationDto yxAuthentication : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("真实姓名", yxAuthentication.getRealName());
            map.put("身份证号", yxAuthentication.getCardNumber());
            map.put("身份证正面", yxAuthentication.getCardFront());
            map.put("身份证反面", yxAuthentication.getCardReverse());
            map.put("状态0审判中1审批通过2审批不通过", yxAuthentication.getStatus());
            map.put("保证金", yxAuthentication.getDeposit());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ApiResult<Object> applyAuthentication(YxAuthenticationDto yxAuthenticationDto) {
        YxAuthentication yxAuthentication=this.baseMapper.selectByUid(yxAuthenticationDto.getUid());
        if(null !=yxAuthentication && 2 !=yxAuthentication.getStatus()){
            throw new YshopException("已认证，请勿重新认证");
        }else if(ObjectUtil.isEmpty(yxAuthentication)){
            yxAuthentication = new YxAuthentication();
        }

        //判断身份证信息是否正确
        String front = DataUtil.NetImageToBase64(yxAuthenticationDto.getCardFront());
        String back = DataUtil.NetImageToBase64(yxAuthenticationDto.getCardReverse());

        String[] str = new String[]{"key","side","image"};
        String[] frontBase64 = new String[]{"72b39727d600273a51b2b9507a3eec65","front",front};
        String[] backBase64 = new String[]{"72b39727d600273a51b2b9507a3eec65","back",back};
        Map<String,Object> fMap = new HashMap<>();
        Map<String,Object> bMap = new HashMap<>();
        try {
            fMap =  VerifyUtil.sendPost("http://apis.juhe.cn/idimage/verify",str,frontBase64);
            bMap =  VerifyUtil.sendPost("http://apis.juhe.cn/idimage/verify",str,backBase64);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(fMap.get("entity") == null || bMap.get("entity") == null) throw new YshopException("身份证异常！");
        String data = fMap.get("entity").toString();
        IdCardResult idCardResult =  JSONObject.toJavaObject(JSONObject.parseObject(data), IdCardResult.class);
        if(ObjectUtil.isEmpty(idCardResult.getResult()) || ObjectUtil.isEmpty(idCardResult.getResult().getIdcard())) throw new YshopException("身份证异常！");
        //判断身份证是否与填入信息一致
        if(!yxAuthenticationDto.getCardNumber().equals(idCardResult.getResult().getIdcard())) throw new YshopException("与证件照身份证号不一致！");
        if(!yxAuthenticationDto.getRealName().equals(idCardResult.getResult().getRealname())) throw new YshopException("与证件照姓名不一致");


        YxAuthentication cardNum=this.baseMapper.selectOne(new QueryWrapper<YxAuthentication>().lambda().eq(YxAuthentication::getCardNumber,yxAuthenticationDto.getCardNumber()).ne(YxAuthentication::getUid,yxAuthenticationDto.getUid()));
        if(null !=cardNum){
            throw new YshopException("该身份证已被认证");
        }
        yxAuthentication.setCardFront(yxAuthenticationDto.getCardFront());
        yxAuthentication.setCardNumber(yxAuthenticationDto.getCardNumber());
        yxAuthentication.setCardReverse(yxAuthenticationDto.getCardReverse());
        yxAuthentication.setRealName(yxAuthenticationDto.getRealName());
        yxAuthentication.setUid(yxAuthenticationDto.getUid());
        yxAuthentication.setStatus(1);
        YxAppdict yxAppdict=yxAppdictService.findAppdictByCode("bzj");
        if(null !=yxAppdict){
            yxAuthentication.setDeposit(new BigDecimal(yxAppdict.getMemo()));
        }else{
            yxAuthentication.setDeposit(new BigDecimal(20));
        }
        this.saveOrUpdate(yxAuthentication);
        return ApiResult.ok("提交认证成功");
    }
}
